using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using Microsoft.SharePoint.StsAdmin;
using Microsoft.SharePoint;

namespace DD.SharePoint.STSADM.Extensions
{
    public class SPUserManagementCommand : ISPStsadmCommand
    {
        #region ISPStsadmCommand Members

        public string GetHelpMessage(string command)
        {
            command = command.ToLowerInvariant();

            switch (command)
            {
                case "setuserproperties":
                    return "-login <Login Name>\n" + 
                        "           [-email <Email Address>]\n" +
                        "           [-displayname <Display Name>]\n";
                default:
                    throw new InvalidOperationException();
            }            
        }

        public int Run(string command, System.Collections.Specialized.StringDictionary keyValues, out string output)
        {
            command = command.ToLowerInvariant();

            switch (command)
            {
                case "setuserproperties":
                    return SetUserProperties(keyValues, out output);
                default:
                    throw new InvalidOperationException();
            }
        }

        private int SetUserProperties(StringDictionary keyValues, out string output)
        {
            if (!keyValues.ContainsKey("url"))
            {
                throw new InvalidOperationException("The url parameter was not specified");
            }

            if (!keyValues.ContainsKey("login"))
            {
                throw new InvalidOperationException("The login parameter was not specified");
            }

            StringBuilder sb = new StringBuilder();

            String url = keyValues["url"];
            String login = keyValues["login"];
            SPWeb web = null;

            try
            {
                web = new SPSite(url).OpenWeb();
            }
            catch (Exception)
            {
                throw new InvalidOperationException("Error retrieving url '" + url + "'.");
            }

            try
            {
                SPUser user = web.SiteUsers[login];
                if (keyValues["email"] != null)
                    user.Email = keyValues["email"];
                if (keyValues["displayname"] != null)
                    user.Name = keyValues["displayname"];
                user.Update();

                sb.Append("Operation successfully completed");
            }
            catch (Exception)
            {
                throw new InvalidOperationException("Operation failed");
            }

            output = sb.ToString();

            return 0;
        }

        #endregion
    }
}
